<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');

require_once('modules/Leads/Lead.php');
require_once('include/SugarObjects/templates/person/Person.php');
class CheckListLeadLogicHook extends Lead {
		/*
		Get num of item by Sales_Stage and Lead_Id
	*/
	function get_no_of_items_updated($Sales_Stage, $Lead_Id)
	{
	   	// module specific
		$sql = "Select count(l.id) as count
		from Leads_Checklist l inner join Lead_Opp_Checklist_Master m on m.id = l.Lead_Opp_Checklist_Master_id
		where l.Checklist_Response <>'' and m.Sales_Stage= '$Sales_Stage' and l.Lead_Id = '$Lead_Id'";
		$result = $this->db->query($sql,true);
		//echo $sql;
		while($row = $this->db->fetchByAssoc($result)){
			return $row["count"];
		}
	}
	/*
		Get num of item by Sales_Stage and Lead_Id
	*/
	function get_num_of_item($Sales_Stage, $Lead_Id)
	{
	   	// module specific
	   	$sql = "Select count(l.id) as count
	   		from Leads_Checklist l inner join Lead_Opp_Checklist_Master m on m.id = l.Lead_Opp_Checklist_Master_id
		where m.Sales_Stage= '$Sales_Stage' and l.Lead_Id = '$Lead_Id'";
		$result = $this->db->query($sql,true);
		
		while($row = $this->db->fetchByAssoc($result)){
			return $row["count"];
		}
	}
   
	/*
		Get sumary all Sales_Stage
	*/
	function get_sumary($Lead_Id)
	{
	   	// module specific
		$sql = "Select distinct '' as Lead_Id, Sales_Stage,0 as No_of_items, 0 as No_of_items_updated
		from Lead_Opp_Checklist_Master where Module_Name = 'Leads' order by Sales_Stage";
		$result = $this->db->query($sql,true);
		
		while($row = $this->db->fetchByAssoc($result)){
		//$value = $_REQUEST['Checklist_Response_'.$item['id']];
			$row["Lead_Id"] = $Lead_Id;
			$row["No_of_items"] = $this->get_num_of_item($row["Sales_Stage"], $Lead_Id);
			$row["No_of_items_updated"] = $this->get_no_of_items_updated($row["Sales_Stage"], $Lead_Id);
			$sumary[] = $row;
		}
		
		return $sumary;
	}
	
  /*
  	Download excel file
  */
  function download_file($focus)
  {
	   	ob_clean();
		ob_start();
		
		//$header = "Opportunity\tChecklist Description\tResponse";
		$header = '"Lead_Name","Sales_Stage","Checklist Description","Response"';
		
	 	// module specific
		$sql = "Select '".$focus->first_name." ".$focus->last_name."' as Lead_Name, m.Sales_Stage, m.Checklist_Item_Desc,l.Checklist_Response
		from Leads_Checklist l inner join Lead_Opp_Checklist_Master m on m.id = l.Lead_Opp_Checklist_Master_id
		where m.Module_Name = 'Leads' and l.Lead_Id ='".$_REQUEST['record']."'";
		$result = $this->db->query($sql,true);
		$data = '';
		while($row = $this->db->fetchByAssoc($result)){
		
			//$value = $_REQUEST['Checklist_Response_'.$item['id']];
		    $line = '';
			foreach($row as $value)
			{
			  if(!isset($value) || $value == "")
			  {
			  		$value = ",";
			  }else
			  {
			         $value = str_replace('"', '""', $value);
			         $value = '"' . $value . '"' . ",";
			  }
			  $line .= $value;
			}
			$data .= trim($line)."\n";
			$data = str_replace("\r", "", $data);

			if ($data == "") {
			$data = "\nno matching records found\n";
			}
		}
		
		header("Pragma: no-cache");
		header("Expires: 0");
		header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
		header("Content-type: application/csv;");
		header('Content-Disposition: attachment; filename="Leads_Checklist.csv"');
		header('Content-Length: '.strlen($header."\n".$data));
		
		// output data
		echo $header."\n".$data;
		exit(); //done outputting csv
  }
     
 	 function after_save_method($bean, $event, $arguments)
    {
    	global $current_user;
        //logic
    	if(isset($_REQUEST['record'])) {
			//display logic
    		$sql = "select * from Leads_Checklist where Lead_Id ='{$bean->id}'";
			$result = $this->db->limitQuery($sql,0,1,true, "Want only a single row");
			$row= $this->db->fetchByAssoc($result);
			
			if(empty($row)){
			 	//create insert query for new campaign log
                $insert_query="insert into Leads_Checklist(Lead_Id,Sales_Stage,Lead_Opp_Checklist_Master_id,Checklist_Response)
				select '{$bean->id}', Sales_Stage, id,'' 
				 from Lead_Opp_Checklist_Master where Module_Name = 'Leads'";
                $this->db->query($insert_query);
			}
		}
    }
    function after_ui_frame_method($event, $arguments)
        {
        	global $current_user;
        
			if(isset($_REQUEST['record'])) {
				//display logic
	          	if($_REQUEST['action']=='DetailView') {
	          		$focus=new Lead();
					$focus->retrieve($_REQUEST['record']);
					if(isset($_REQUEST['use_adv'])) {
		          		if($_REQUEST['use_adv'] == 'Checklist')
		          		{
		          				// module specific
								$sql = "Select id	from Leads_Checklist where Lead_Id ='".$_REQUEST['record']."'";
								$result = $this->db->query($sql,true);
								$value = '';
								$update_query = '';
								while($item   = $this->db->fetchByAssoc($result)){
								
									$value = $_REQUEST['Checklist_Response_'.$item['id']];
								    //create insert query for new campaign log
					                $update_query ="update Leads_Checklist set Checklist_Response = '{$value}'
					                	where id = '{$item['id']}';";
					        	 	$this->db->query($update_query);        
								}
		          		}
		          		else if($_REQUEST['use_adv'] == 'excel')
		          		{
		          			$this->download_file($focus);
		          		}
	          		}
	          		
					// module specific
					$sql = "Select l.id, Lead_Id, m.Sales_Stage,m.Allowed_Responses,m.Checklist_Item_Type,m.Checklist_Item_Desc,m.Checklist_Item_Name,
							m.no_of_rows,m.back_color, l.Checklist_Response
					from Leads_Checklist l inner join Lead_Opp_Checklist_Master m on m.id = l.Lead_Opp_Checklist_Master_id
					where m.Module_Name = 'Leads' and l.Lead_Id ='".$_REQUEST['record']."'
					order by m.checklist_sort_order";
					$result = $this->db->query($sql,true);
					
					while($item   = $this->db->fetchByAssoc($result)){
					    $checklists[] = $item;
					}
					$this->createFormHTML($focus,$checklists);
				}
			}
        }
        
        
	function createFormHTML($focus,$checklists) {
		global $mod_strings;
		global $app_list_strings;
		global $app_strings;
		global $current_user;

		// TEMPLATE ASSIGNMENTS
		$xtpl = new XTemplate('custom/modules/Leads/CheckListLeadEditView.html');
		// standard assigns
		$xtpl->assign('MOD', $mod_strings);
		$xtpl->assign('APP', $app_strings);
		
		$xtpl->assign('RETURN_MODULE', 'Leads');
		$xtpl->assign('ID', $focus->id);
		$xtpl->assign('RETURN_ID', $focus->id);
		$xtpl->assign('RETURN_ACTION', 'DetailView');
		 // another way to do it would be:
        $rowsize = count($checklists);
        for ($i = 0; $i < $rowsize; $i++) {
        // assign array data
        	$xtpl->assign('data', $checklists[$i]);
        	
        	if($checklists[$i]['Checklist_Item_Type'] == 'Dropdown')
        	{
        		$select = "<select name='Checklist_Response_".$checklists[$i]['id']."' style=\"width: 200px\">";
        		$arr = null;
        		if($checklists[$i]['Allowed_Responses'] <> '')
        		{
	        		$list = explode( ',', ','.$checklists[$i]['Allowed_Responses'] );
	        		//create the type dropdown domain and set the selected value if $opp value already exists
					foreach ($list as $key => $value) {
					    // echo "Key: $key; Value: $value<br />\n";
					    $arr[$value] = $value;
					}
        			$select .=get_select_options_with_id($arr , $checklists[$i]['Checklist_Response']);
        		}
        		$select .="</select>";
        		$xtpl->assign('Checklist_Response', $select);
        	}
        	else
        	{
        		$xtpl->assign('Checklist_Response', "<textarea name='Checklist_Response_".$checklists[$i]['id']."'  rows=\"".$checklists[$i]['no_of_rows']."\" cols=\"100\">".$checklists[$i]['Checklist_Response']."</textarea>");
        	}
        	
        	 // parse a row
	        $xtpl->parse('main.table.row');
		}
		
		$sumary = $this->get_sumary($focus->id);
		$rowsize = count($sumary);
	 	for ($i = 0; $i < $rowsize; $i++) {
	        // assign array data
	        	$xtpl->assign('sumary', $sumary[$i]);
	        	 // parse a row
		        $xtpl->parse('main.table2.row2');
		}
		
		$xtpl->assign('STATUS', $focus->status);
		$sales = null; 
		$lead_status_dom = $app_list_strings['lead_status_dom'];
		asort($lead_status_dom);
		foreach ($lead_status_dom as $key => $value) {
		    $sales[$value] = $value;
		}
	
		$xtpl->assign('STATUS_OPTIONS',get_select_options_with_id($sales , $focus->status));
		 // parse the table
	    $xtpl->parse('main.table');
	    $xtpl->parse('main.table2');
		$xtpl->parse("main");
		$xtpl->out("main");
	}

    }

?>